package com.dawn.gameNow.net {

    public class Connection {

        private var _socket:Socket;
        private var responseData:ByteArray = new ByteArray();

        public function Connection() {
        }

        public function ConnectTo(ip:String, port:int):void {

            _socket = new Socket();
            _socket.addEventListener(Event.ACTIVATE, onActive);
            _socket.addEventListener(Event.CLOSE, onClose);
            _socket.addEventListener(ProgressEvent.SOCKET_DATA, onSocketData);
            _socket.addEventListener(Event.CONNECT, onConnect);
            _socket.addEventListener(IOErrorEvent.IO_ERROR, onIOError);
            _socket.addEventListener(SecurityErrorEvent.SECURITY_ERROR, onSecurityError);
            _socket.connect(ip, port);
        }

        public function close():void {

        }

        public function get socket():Socket {
            return _socket;
        }

        private function onActive(e:Event):void {
            //trace("onActive");
        }

        private function onClose(e:Event):void {
            trace("onClose");
        }

        private function onConnect(e:Event):void {
            trace("onConnect");
        }

        private function onIOError(e:Event):void {
            trace("onIOError");
        }

        private function onSecurityError(e:Event):void {
            mx.controls.Alert("onSecurityError");
            trace("onSecurityError");
        }

        private function onSocketData(e:Event):void {
            trace("onSocketData---------------------");

            var data:ByteArray = new ByteArray();
            this._socket.readBytes(data);
            this.dataProcesser.process(data);

        }

        public function send(ba:ByteArray):void {

            if (this._socket.connected) {
                trace("send data");
                this._socket.writeBytes(ba, 0, ba.length);
                this._socket.flush();
            }
        }

        public function process(ba:ByteArray) {
            var op:int = DataUtil.readInt(responseData, 4);

            if (Core.handlerMap.hasOwnProperty(op)) {
                Core.handlerMap[op](responseData, len);
            }

        }
    }
}